import React from 'react';
import { connect } from 'react-redux';
import { Button, Row, Col, message, Tooltip, Input, Icon } from 'antd';
import List from './list';
import { getFeildByTreeData } from 'src/utils/utils';
import CommonListsIndex from '../../../components/CommonLists/index';
import SearchBar from 'src/components/SearchBar';
import PolicyAdd from './add';
import TempalteAddStrategy from './form/tempalteAddStrategy';
import ToTemplate from '../StrategyTemplate/toTemplate';
import services from '../../../services/api';
import AuditStatus from '../../../components/AuditStatus';
import Modal from '../../../components/Modal/index';
import storage from '../../../utils/storage';
import { AUDIT } from '../../../utils/constant';

function mapStateToProps(state) {
  return {
    strategy_type: state.code.strategy_type || [],
    strategy_mode: state.code.strategy_mode || [],
    orgList: state.global.orgList,
    strategy_name: state.global.name,
  };
}

@connect(mapStateToProps)
class PolicyIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'strategyFlow';
    this.addComponent = PolicyAdd;
    this.editComponent = '/strategy/config/id/edit';
    this.copyComponent = '/strategy/config/id/copy';
    this.detailComponent = '/strategy/config/id/detail';
    this.listsComponent = List;
    this.state = {
      ...this.state,
      riskTypes: [],
      columns: [],
      dataIndex: 'strategy_type',
      selectedRowKeys: [],
      currentEventId: '',
      selectedRows: [],
    };
    if (this.app_id) {
      this.queryTableParams.app_id = this.app_id;
    }
    if (this.event_id) {
      this.queryTableParams.event_id = this.event_id;
    }
    if (this.field_id) {
      this.queryTableParams.field_id = this.field_id;
    }
    if (this.feature_id) {
      this.queryTableParams.feature_id = this.feature_id;
    }
  }
  componentDidMount() {
    const locationState = this.props.history.location;
    if (locationState.state && locationState.state.name) {
      this.queryParams.projectName = locationState.state.name;
    }
    this.freshQueryList();
    // this.getAppCodeList();
    // this.getProductCodeList();
    // this.getRiskTypeList();
    // storage.strategyExport = []; // 首次进入清空storage.strategyExport
  }

  // 搜索内容
  getSearchList = () => {
    return [
      {
        name: 'projectName',
        component: <Input placeholder='项目名称' />,
      },
      {
        name: 'name',
        component: <Input placeholder='策略名称' />,
      },
      {
        name: 'createBy',
        component: <Input placeholder='创建人' />,
      },
      {
        name: 'updateBy',
        component: <Input placeholder='修改人' />,
      },
    ];
  };

  // 获取风险类型列表
  getRiskTypeList = () => {
    services.policy.riskTypeList().then((res) => {
      if (res.code === 0) {
        this.setState({
          riskTypes: res.data,
        });
      }
    });
  };

  // 策略导入回调
  onChange = (info) => {
    this.freshQueryList();
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 导入成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 导入失败`);
    }
  };
  // 转为模板
  showTemplate = (record) => {
    Modal.open({
      title: '转为模板',
      width: '600px',
      content: (
        <ToTemplate
          value={record}
          closeModel={() => {
            Modal.close();
          }}
        />
      ),
      isOkBtn: false,
      isCancelBtn: false,
      ok: () => {
        Modal.close();
      },
    });
  };
  // 从模板新增策略
  showTemplateAddStatege = (record) => {
    Modal.open({
      title: '从模板新增策略',
      width: '800px',
      content: (
        <TempalteAddStrategy
          {...this.props}
          closeModel={() => {
            Modal.close();
          }}
        />
      ),
      isOkBtn: false,
      isCancelBtn: false,
      ok: () => {
        Modal.close();
      },
    });
  };
  // 详情
  showDetail = (record) => {
    this.props.history.push(this.replaceUrlForId(this.detailComponent, this.getOpenParam(record)));
  };

  // 复制
  copy = (record) => {
    this.props.history.push(this.replaceUrlForId(this.copyComponent, this.getOpenParam(record)));
  };

  // 表列定义
  getColumns = () => {
    const { orgList } = this.props;
    return [
      {
        title: '所属机构',
        key: 'orgCode',
        dataIndex: 'orgCode',
        width: 100,
        ellipsis: true,
        render: (text) => {
          const name = getFeildByTreeData({
            tree: orgList,
            souceVal: text,
          }).name;
          return (
            <Tooltip title={name} placement='topLeft'>
              <div className='overflowtext'>{name}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '所属项目',
        key: 'projectName',
        width: 100,
        dataIndex: 'projectName',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext'>{text}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '策略名称',
        key: 'name',
        width: 100,
        dataIndex: 'name',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext'>{text}</div>
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      {
        title: '策略code',
        key: 'code',
        width: 100,
        dataIndex: 'code',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext'>{text}</div>
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      {
        title: '最新可用版本',
        key: 'version',
        width: 130,
        dataIndex: 'version',
        render: (text, record) => {
          return text ? <span style={{ color: '#00a600' }}>{'v' + text}</span> : '';
        },
      },
      {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        width: 100,
        render: (text, record) => {
          return text === 0 ? (
            <div>
              草稿
              <Tooltip title={`草稿状态的策略不可进行发布。若配置完成，请提交后再发布`}>
                <Icon type='info-circle' />
              </Tooltip>
            </div>
          ) : (
            <span>{'已完成'}</span>
          );
        },
      },
      {
        title: '变更提示',
        key: 'tipStatus',
        width: 100,
        dataIndex: 'auditipStatust_label',
        render: (text, record) => {
          return (
            <div>
              <Button type='link'>查看</Button>
              {text && <Icon type='exclamation-circle' />}
            </div>
          );
        },
      },
      {
        title: '修改时间',
        key: 'updateAt',
        dataIndex: 'updateAt',
        width: 150,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext' style={{ width: '80%' }}>
                {text}
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '创建/修改人',
        key: 'createBy',
        width: 150,
        dataIndex: 'createBy',
        render: (text, record) => {
          return (
            <Tooltip title={`${record.createBy}/${record.updateBy}`}>
              <div className='overflowtext'>{`${record.createBy || '-'}/${record.updateBy || '-'}`}</div>
            </Tooltip>
          );
        },
      },
      {
        title: '审核状态',
        key: 'auditStatus',
        width: 150,
        dataIndex: 'auditStatus',
        render: (text, record) => {
          return <span>{text === 0 ? '待审核' : text === 1 ? '已通过' : text === 2 ? '已拒绝' : '-'}</span>;
          // return <AuditStatus text={text} record={record} />;
        },
      },
    ];
  };

  export = () => {
    if (this.state.selectedRowKeys.length === 0) {
      message.warning('请选择要导出的策略');
      return;
    }
    const params = {
      strategy_ids: this.state.selectedRowKeys.join(),
    };
    services.policy
      .submit(params)
      .then((res) => {
        if (!res.code) {
          this.props.history.push('/strategy/config/export');
        }
      })
      .catch((err) => {
        message.error(err);
      });
  };

  // 删除回调
  deleteCb = (record) => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) return;
    if (selectedRowKeys.indexOf(record.strategy_id) !== -1) {
      let newKeys = selectedRowKeys.filter((item) => item !== record.strategy_id);
      let newRows = selectedRows.filter((item) => item.strategy_id !== record.strategy_id);
      if (newKeys.length === 0) this.setState({ currentEventId: '' });
      this.setState(
        {
          selectedRowKeys: newKeys,
          selectedRows: newRows,
        },
        () => {
          const exportMsg = {
            selectedRowKeys: this.state.selectedRowKeys,
            currentEventId: this.state.currentEventId,
          };
          storage.strategyExportMsg = exportMsg;
        },
      );
    }
  };

  render() {
    const ListsComponent = this.listsComponent;
    return (
      <div>
        <SearchBar
          searchList={this.getSearchList()}
          query={this.freshQueryList}
          onChange={this.refreshFilter}
          reset={this.resetListAndSearch}
        />

        <div className='inner-content' style={{ marginTop: '10px' }}>
          <Row type='flex' justify='space-between' align='middle' className='pb-10'>
            <Col span={12}>
              <Button
                type='primary'
                onClick={() => {
                  this.props.history.push('/strategy/config/add');
                }}
              >
                新建策略
              </Button>
            </Col>
          </Row>
          <ListsComponent
            {...this.state}
            {...this.props}
            edit={this.edit}
            onChangePagination={this.onChangePagination}
            scroll={{ x: true }}
            showDetail={this.showDetail}
            toTemplate={this.showTemplate}
            copy={this.copy}
            defaultColumns={this.state.defaultColumns}
            columns={this.getColumns()}
            queryList={this.freshQueryList}
            rowKey='id'
            deleteCb={this.deleteCb}
          />
        </div>
      </div>
    );
  }
}

export default PolicyIndex;
